package com.kq.myofficialaccount.controller;

import com.kq.myofficialaccount.service.WxService;
import com.kq.myofficialaccount.utils.WxUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/wx")
@RestController
@Slf4j
public class WxController {

    @Resource
    WxService wxService;

    /**
     * 微信 url 验证接口
     */
    @GetMapping("/")
    public String wxCheck(@RequestParam("signature") String signature,
                        @RequestParam("timestamp") Integer timestamp,
                        @RequestParam("nonce") String nonce,
                        @RequestParam("echostr") String echostr) {
        log.info("开始验证 url signature={}，timestamp={}，nonce={}，echostr={}", signature,
                timestamp, nonce, echostr);
        //TODO:验证是微信发送的
        return echostr;
    }

    /**
     * 接收消息并自动回复的功能
     */
    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request) throws IOException, DocumentException {
        ServletInputStream inputStream = request.getInputStream();
        // 将传来的信息封装到 map 中
        HashMap<String, String> map  = new HashMap<>();
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(inputStream);
        Element rootElement = read.getRootElement();
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            map.put(element.getName(), element.getStringValue());
        }
        // 拿到用户的 OpenId
        String openId = map.get("FromUserName");
        // 验证是扫码登录且事件值是1  || (map.get("Event").equals("subscribe"))
        //TODO：给事件值封装一个常量类
        if ((map.get("Event").equals("subscribe") || map.get("Event").equals("SCAN")) &&
                map.get("EventKey").equals("1")) {
            String token = wxService.WxLogin(openId);
            return WxUtil.getReplyMessage(map, "你的登录密钥为：" + token);
        }
        return "";
    }


}
